"""Service management utilities for vLLM and Ollama."""

import subprocess
import time
from typing import Optional


class ServiceManager:
    """Manages vLLM and Ollama service lifecycle."""
    
    @staticmethod
    def stop_ollama():
        """Stop Ollama service."""
        print("\n🛑 Stopping Ollama service...")
        try:
            subprocess.run(["systemctl", "stop", "ollama"], check=False, capture_output=True)
            subprocess.run(["pkill", "-f", "ollama"], check=False, capture_output=True)
            time.sleep(3)
            print("   ✅ Ollama stopped")
        except Exception as e:
            print(f"   ⚠️  Failed to stop Ollama: {e}")
    
    @staticmethod
    def start_ollama():
        """Start Ollama service."""
        print("\n🚀 Starting Ollama service...")
        try:
            subprocess.run(["systemctl", "start", "ollama"], check=False, capture_output=True)
            time.sleep(5)
            print("   ✅ Ollama started")
        except Exception as e:
            print(f"   ⚠️  Failed to start Ollama: {e}")
    
    @staticmethod
    def stop_vllm():
        """Stop vLLM service."""
        print("\n🛑 Stopping vLLM service...")
        try:
            subprocess.run(["pkill", "-f", "vllm.entrypoints.openai.api_server"], check=False, capture_output=True)
            time.sleep(3)
            print("   ✅ vLLM stopped")
        except Exception as e:
            print(f"   ⚠️  Failed to stop vLLM: {e}")
    
    @staticmethod
    def start_vllm():
        """
        Start vLLM service.
        Note: This typically requires running a startup script separately.
        """
        print("\n⚠️  vLLM must be started using scripts/start_vllm.sh")
        print("   This function only provides a placeholder.")
    
    @staticmethod
    def check_service_status(service: str) -> Optional[str]:
        """
        Check if a service is running.
        
        Args:
            service: Service name ('vllm' or 'ollama')
            
        Returns:
            Service status string or None
        """
        try:
            if service.lower() == "vllm":
                result = subprocess.run(
                    ["pgrep", "-f", "vllm.entrypoints.openai.api_server"],
                    capture_output=True,
                    text=True
                )
                if result.returncode == 0:
                    return "running"
                return "stopped"
            elif service.lower() == "ollama":
                result = subprocess.run(
                    ["pgrep", "-f", "ollama"],
                    capture_output=True,
                    text=True
                )
                if result.returncode == 0:
                    return "running"
                return "stopped"
        except Exception as e:
            return f"error: {e}"
        
        return None

